import axios, { type AxiosResponse } from 'axios'
import { useAuthStore } from '@/store'


const service = axios.create({
	BASE_URL: '/chatbot'
})

service.interceptors.request.use(
  (config) => {
    const token = useAuthStore().token
    if (token)
      config.headers.Authorization = `Bearer ${token}`
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  (response: AxiosResponse): AxiosResponse => {
    if (response.status === 200)
      return response

    throw new Error(response.status.toString())
  },
  (oError) => {
		if (oError.response && oError.response.data && oError.response.data.errors) {
			oError.response.data.errors.forEach(error => {
				switch (error.code) {
					case 'access_denied':
						// token 无效 重新请求
						useAuthStore().removeToken()
						window.location.reload();
						break;
				}
			});
		}
		return Promise.reject(oError);
  },
)

export default service
